import {
  login,
  getInfo,

} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo,
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'


const getDefaultState = () => {
  return {
    token: getToken(), //token
    userInfo: getUserInfo(), //用户信息
    name: '', //用户名称
    avatar: '', //用户头像,
    myData: '',
    roles: [], //用户权限
    unit: localStorage.getItem('YYY_Unit') ? localStorage.getItem('YYY_Unit') : 'USD', //RMB:人民币，USD:'美元',
    isInvite: '', //判断接受或者拒绝邀请
    unit: localStorage.getItem('YYY_Unit') ? localStorage.getItem('YYY_Unit') : 'USD', //RMB:人民币，USD:'美元'
    timeZone: localStorage.getItem('YYY_TimeZone') ? localStorage.getItem('YYY_TimeZone')==='CN'?'ORTZ':'UTC' : 'UTC',
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 设置token
  SET_TOKEN: (state, token) => {
    setToken(token)
    state.token = token
  },
  // 设置用户信息
  SET_USER_INFO: (state, info) => {
    info.roleName = info.roleName ? info.roleName : '',
    setUserInfo(info)
    state.userInfo = info;
  },
  SET_PUBLIC: (state, data) => {
    state.myData = data
  },

  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },

  SET_ROLES: (state, roles) => {
    state.roles = roles
  },

  // 设置海外或大陆
  SET_UNIT: (state, type) => {
    localStorage.setItem('YYY_Unit', type)
    state.unit = type
  },
  SET_TIMEZONE: (state, type) => {
    localStorage.setItem('YYY_TimeZone', type);
    state.timeZone = type;
  },

  SET_INVITE: (state, isInvite) => {
    state.isInvite = isInvite
    // 设置时区
  }

}

const actions = {
  // 用户登录
  login({
    commit
  }, userInfo) {
    return new Promise((resolve, reject) => {
      login({ ...userInfo
      }).then(response => {
        const {
          data
        } = response;
        // data.data
        // id: 10101
        // roleName: "customer"
        // token: "eyJhbGciO
        if (data.code === 20000) {
          commit('SET_TOKEN', data.data.token);
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (response.data.code !== 20000) {
          reject('Verification failed, please Login again.')
        } else {
          let roleName = response.data.data.roleName ? response.data.data.roleName : 'visitor'
          response.data.data.roleName = {
            roleName: roleName,
            ...response.data.data
          }
          const {
            data
          } = response.data
          commit('SET_USER_INFO', {
            ...data,
            UserName: 'admin',
            roleName: 'visitor',
          });
          resolve(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      try {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken();
        removeUserInfo();
        resetRouter();
        resolve('成功退出');
      } catch {
        reject('退出失败');
      }
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }


}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
